﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class AdminAnuncio : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
  {
      this.Title = AcheiCampinasConfiguration.SiteName +
           " : administrar produtos ou serviços.";
    // Load the grid only the first time the page is loaded
    if (!Page.IsPostBack)
    {
     
      // Load the products grid
      BindGrid();
    }
  }

  // Populate the GridView with data
  private void BindGrid()
  {
    string empresaId = Request.QueryString["EmpresaID"];
    DataTable empresaInfo = CatalogAccess.GetInformacoesEmpresa(empresaId);
    DataRow row = empresaInfo.Rows[0];
    infoLabel.Text = "<strong>Empresa: </strong>" + row["nome"] + "<strong> - Qtdd. anúncios: </strong>" + row["qtddProdutos"] + "<strong> - Limite: </strong>" + row["limiteProdutos"] + "<br /><br />";
    
    // Get a DataTable object containing the products
    grid.DataSource = CatalogAccess.GetAllProductsEmpresa(empresaId);

    grid.DataBind();

    if (grid.Rows.Count == 0)
        statusLabel.Text = "Não há produtos ou serviços cadastrados";
  }

  // Enter row into edit mode
  protected void grid_RowEditing(object sender, GridViewEditEventArgs e)
  {
    // Set the row for which to enable edit mode
    grid.EditIndex = e.NewEditIndex;
    // Set status message 
    statusLabel.Text = "Editando produto/serviço #: " + e.NewEditIndex.ToString();
    // Reload the grid
    BindGrid();
  }

  // Cancel edit mode
  protected void grid_RowCancelingEdit(object sender,
  GridViewCancelEditEventArgs e)
  {
    // Cancel edit mode
    grid.EditIndex = -1;
    // Set status message
    statusLabel.Text = "Edição cancelada";
    // Reload the grid
    BindGrid();
  }

  // Update a product
  protected void grid_RowUpdating(object sender, GridViewUpdateEventArgs e)
  {
    // Retrieve updated data
    try
    {
      string id = grid.DataKeys[e.RowIndex].Value.ToString();
      string name = ((TextBox)grid.Rows[e.RowIndex].FindControl("nameTextBox")).Text;
      string description = ((TextBox)grid.Rows[e.RowIndex].FindControl("descriptionTextBox")).Text;
      string price = ((TextBox)grid.Rows[e.RowIndex].FindControl("priceTextBox")).Text;
      // Execute the update command
      bool success = CatalogAccess.UpdateProduct(id, name, description, price);
      // Cancel edit mode
      grid.EditIndex = -1;
      // Display status message
      statusLabel.Text = success ? "Produto Atualizado com sucesso." : "A atualização falhou.";
    }
    catch
    {
      // Display error
      statusLabel.Text = "A atualização falhou.";
    }
    // Reload grid
    BindGrid();
  }
}
